<template>
  <div>
    <!-- 企业基本信息填写 -->
    <el-form v-show="step === 1" :model="form" :rules="rules" :label-width="220" ref="formRef1">
      <LeftTip className="mt-3" title="基本信息" />
      <el-form-item v-if="route.query.productId" label="产品名称">
        <el-input v-model="form.productName" size="large" readonly placeholder="请输入产品名称"></el-input>
      </el-form-item>
      <el-form-item v-if="route.query.productId" label="所属机构">
        <el-input v-model="form.organizationName" size="large" readonly placeholder="请输入所属机构"></el-input>
      </el-form-item>

      <el-form-item label="企业名称：" prop="enterpriseId">
        <el-select size="large" @change="selectMyEnterprise" v-model="form.enterpriseId" placeholder="请选择企业">
          <el-option v-for="item in enterpriseList" :key="item.id" :label="item.enterpriseName"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="企业人数：" prop="information.staffNum">
        <el-select size="large" v-model="form.information.staffNum" placeholder="请选择企业人数">
          <el-option v-for="item in numberOfCompanyOptions" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="企业行业：" prop="information.industry">
        <el-select size="large" v-model="form.information.industry" placeholder="请选择企业行业">
          <el-option v-for="item in enterpriseIndustryOptions" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
        <!-- <el-cascader ref="industryRef" class="!w-full" @change="industryChanges" v-model="form.information.industry"
          size="large" placeholder="请选择企业行业" :options="industryOptions" /> -->
      </el-form-item>

      <el-form-item label="注册资本：" prop="information.registeredCapital">
        <el-input size="large" v-model="form.information.registeredCapital" placeholder="请输入注册资本">
          <template #append>
            <div>万元</div>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="是否小微企业：" prop="microFlag">
        <el-radio-group v-model="form.microFlag" size="large">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="企业开户行：" prop="information.depositBank">
        <el-select size="large" v-model="form.information.depositBank" placeholder="请选择企业开户行">
          <el-option v-for="(item, i) in loanBankOptions" :key="i" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="已持续经营年限：" prop="information.durationManagement">
        <el-input size="large" v-model="form.information.durationManagement" placeholder="请输入已持续经营年限">
          <template #append>
            <div>年</div>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="企业所在区域：" prop="information.corrProvinceSiteId">
        <cityChoose :readonly="true" v-model:provinceSiteId="form.information.corrProvinceSiteId"
          v-model:citySiteId="form.information.corrCitySiteId" v-model:areaSiteId="form.information.corrAreaSiteId" />
      </el-form-item>

      <el-form-item label="企业经营地址：" prop="information.corrAddress">
        <el-input size="large" v-model="form.information.corrAddress" placeholder="请输入企业经营地址"></el-input>
      </el-form-item>

      <el-form-item label="单位电话：" prop="information.workTelephone">
        <el-input v-model="form.information.workTelephone" size="large" placeholder="请输入单位电话"></el-input>
      </el-form-item>

      <el-form-item label="企业联系人：" prop="enterpriseContactor">
        <el-input size="large" v-model="form.enterpriseContactor" placeholder="请输入企业联系人"></el-input>
      </el-form-item>

      <el-form-item label="联系人手机：" prop="contactorTell">
        <el-input size="large" v-model="form.contactorTell" placeholder="请输入联系人手机"></el-input>
      </el-form-item>

      <LeftTip className="mt-3" title="企业主/经营者信息" />

      <el-form-item label="法定代表人/经营者：" prop="legal.name">
        <el-input size="large" readonly v-model="form.legal.name"></el-input>
      </el-form-item>

      <el-form-item label="现居住地址：" prop="legal.legalLiveAddress">
        <el-input size="large" v-model="form.legal.legalLiveAddress" placeholder="请输入现居住地址"></el-input>
      </el-form-item>

      <el-form-item label="从业年限：" prop="legal.employmentYears">
        <el-input size="large" v-model="form.legal.employmentYears" placeholder="请输入从业年限"></el-input>
      </el-form-item>

      <el-form-item label="持股比例：" prop="legal.shareholdingRatio">
        <el-slider v-model="form.legal.shareholdingRatio" />
      </el-form-item>

      <el-form-item class="mt-10">
        <div class="w-full text-center">
          <el-button type="primary" size="large" @click="finishEnterpriseInfo" class="!text-4.5 w-50"> 下一步 </el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 企业补充信息填写 -->
    <el-form v-show="step === 2" :model="form" :rules="rules" :label-width="220" ref="formRef2">
      <LeftTip className="mt-3" title="补充信息" />

      <el-form-item label="营业场所性质：" prop="information.businessPlace">
        <el-select size="large" v-model="form.information.businessPlace" placeholder="请选择营业场所性质：">
          <el-option v-for="(item, i) in businessPremisesOptions" :key="i" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="上一年度开票营业收入：" prop="incomeData">
        <el-select size="large" v-model="form.incomeData" placeholder="请选择上一年度开票营业收入：">
          <el-option v-for="(item, i) in invoicingOperatingIncome" :key="i" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="上一年度纳税金额：" prop="taxAmount">
        <el-select size="large" v-model="form.taxAmount" placeholder="请选择上一年度纳税金额">
          <el-option v-for="(item, i) in taxAmountOptions" :key="i" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="上一年度报关成交额：" prop="information.declareDeal">
        <el-input size="large" v-model="form.information.declareDeal" placeholder="请输入上一次报关成交额">
          <template #append>
            <div>万元</div>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="纳税等级：" prop="information.taxLevel">
        <el-select size="large" v-model="form.information.taxLevel">
          <el-option v-for="(item, i) in ratepayingLevelOptions" :key="i" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="近一年企业盈亏状态：" prop="profitState">
        <el-select size="large" v-model="form.profitState" placeholder="请选择近一年企业盈亏状态">
          <el-option v-for="(item, i) in enterpriseProfitOptions" :key="i" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="连续纳税年限：" prop="taxYears">
        <el-input type="number" size="large" v-model="form.taxYears" placeholder="请输入连续纳税年限">
          <template #append>
            <div>年</div>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="抵押物类型：" prop="collateralFlag">
        <el-select v-model="form.collateralFlag" size="large" placeholder="请选择抵押物类型">
          <el-option v-for="(item, i) in pawnTypeOptions" :key="i" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="之前贷款银行：" prop="loanBankName">
        <el-select size="large" v-model="form.loanBankName" placeholder="请选择之前贷款银行">
          <el-option v-for="(item, i) in loanBankOptions" :key="i" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="当前贷款余额：" prop="loanLeftAmount">
        <el-input size="large" v-model="form.loanLeftAmount" placeholder="请输入当前贷款余额"></el-input>
      </el-form-item>

      <el-form-item class="mt-10">
        <div class="w-full text-center">
          <el-button size="large" class="!text-4.5 w-50" @click="prev"> 上一步 </el-button>
          <el-button type="primary" size="large" @click="finishSuppleInfo" class="!text-4.5 w-50"> 下一步 </el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 融资需求填写 -->
    <el-form v-show="step === 3" :model="form" :rules="rules" :label-width="220" ref="formRef3">
      <LeftTip className="mt-3" title="融资需求" />

      <el-form-item label="融资金额（万元）：" prop="applyAmountMin">
        <el-input class="!w-30" size="large" v-model="form.applyAmountMin" placeholder="最低金额"></el-input>
        <span class="mx-3">-</span>
        <el-input class="!w-30" size="large" v-model="form.applyAmountMax" placeholder="期望金额"></el-input>
      </el-form-item>

      <el-form-item label="融资期限（月）：" prop="maturityMin">
        <el-input class="!w-30" size="large" v-model="form.maturityMin" placeholder="最短期限"></el-input>
        <span class="mx-3">-</span>
        <el-input class="!w-30" size="large" v-model="form.maturityMax" placeholder="期望期限"></el-input>
      </el-form-item>

      <el-form-item label="融资年利率（%）：" prop="rateMin">
        <el-input class="!w-30" size="large" v-model="form.rateMin" placeholder="最低利率"></el-input>
        <span class="mx-3">-</span>
        <el-input class="!w-30" size="large" v-model="form.rateMax" placeholder="期望利率"></el-input>
      </el-form-item>

      <el-form-item label="期望到账时间：" prop="arrivalTimeType">
        <el-select size="large" v-model="form.arrivalTimeType" placeholder="请选择期望到账时间">
          <el-option v-for="(item, i) in expectedArrivalDateOptions" :key="i" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="期望还款方式：" prop="repaymentType">
        <el-select size="large" v-model="form.repaymentType" placeholder="请选择期望还款方式">
          <el-option v-for="(item, i) in repayWayOptios" :key="i" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="担保类型：" prop="guaranteeType">
        <el-select size="large" v-model="form.guaranteeType" placeholder="请选择担保类型">
          <el-option v-for="(item, i) in guaranteeTypeOptions" :key="i" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item class="mt-10">
        <div class="w-full text-center">
          <el-button size="large" class="!text-4.5 w-50" @click="prev"> 上一步 </el-button>
          <el-button type="primary" size="large" @click="finishFinancingInfo" class="!text-4.5 w-50"> 提交 </el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 融资企业信息预览 -->
    <div v-show="step === 4">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="融资需求信息" name="first">
          <el-descriptions class-name="text-center" border :column="2" size="large">
            <el-descriptions-item align="center" label="融资金额">
              {{ form.applyAmountMin }}-{{ form.applyAmountMax }}万元
            </el-descriptions-item>
            <el-descriptions-item align="center" label="融资期限">
              {{ form.maturityMin }}-{{ form.maturityMax }}个月
            </el-descriptions-item>
            <el-descriptions-item align="center" label="融资年利率">
              {{ form.rateMin }}-{{ form.rateMax }}%
            </el-descriptions-item>
            <el-descriptions-item align="center" label="期望到账时间">
              {{ form.arrivalTimeType }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="还款方式">
              {{ form.repaymentType }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="担保类型">
              {{ form.guaranteeType }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="申请时间">
              {{ new Date().toLocaleString() }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="企业信息" name="second">
          <el-descriptions class-name="text-center" border :column="2" size="large">
            <el-descriptions-item align="center" label="企业名称">
              {{ form.information.enterpriseName }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="统一社会信用代码">
              {{ form.information.creditCode }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="企业人数">
              {{ form.information.staffNum }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="企业行业">
              <el-tooltip class="box-item" effect="dark" :content="form.information.industryName"
                placement="bottom-start">
                <span class="truncate w-30 inline-block">{{ form.information.industryName }}</span>
              </el-tooltip>
            </el-descriptions-item>
            <el-descriptions-item align="center" label="是否小微企业">
              {{ form.information.microFlag == 1 ? '是' : '否' }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="企业所在区域">
              <el-tooltip class="box-item" effect="dark"
                :content="`${form.information.provinceName}/${form.information.cityName}/${form.information.areaName}`"
                placement="bottom-start">
                <span class="truncate w-30 inline-block">{{ form.information.provinceName }}/{{
                  form.information.cityName }}/{{
                    form.information.areaName }}</span>
              </el-tooltip>
            </el-descriptions-item>
            <el-descriptions-item align="center" label="注册地址">
              {{ form.information.legalAddress }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="经营地址">
              <el-tooltip class="box-item" effect="dark"
                :content="`${form.information.corrProvinceSiteName}/${form.information.corrCitySiteName}/${form.information.corrAreaSiteName}`"
                placement="bottom-start">
                <span class="truncate w-30 inline-block">{{ form.information.corrProvinceSiteName }}/{{
                  form.information.corrCitySiteName }}/{{
                    form.information.corrAreaSiteName }}</span>
              </el-tooltip>
            </el-descriptions-item>
            <el-descriptions-item align="center" label="企业法人">
              {{ form.legal.name }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="企业联系人">
              {{ form.enterpriseContactor }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="联系电话">
              {{ form.contactorTell }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="企业盈亏状态">
              {{ transformDict('enterpriseProfit', form.profitState) }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="上年度开票营业收入">
              {{ form.incomeData }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="上年度纳税金额">
              {{ form.taxAmount }}万元
            </el-descriptions-item>
            <el-descriptions-item align="center" label="连续纳税金额">
              {{ form.taxYears }}年
            </el-descriptions-item>
            <el-descriptions-item align="center" label="抵押物类型">
              {{ transformDict('pawnType', form.collateralFlag) }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="开户行">
              <!-- {{form}} -->
              {{ transformDict('loanBank', form.information.depositBank) }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="之前贷款银行">
              <!-- 100-200万元 -->
              {{ transformDict('loanBank', form.loanBankName) }}
            </el-descriptions-item>
            <el-descriptions-item align="center" label="当前贷款余额">
              <!-- 100-200万元 -->
              {{ form.loanLeftAmount }}
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>
      <div class="w-full text-center mt-10">
        <el-button size="large" class="!text-4.5 w-50" @click="prev"> 上一步 </el-button>
        <el-button type="primary" size="large" @click="submitAllInfo" class="!text-4.5 w-50"> 完成 </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getEenterpriceList } from '@/api/enterprise'
import { cloneDeep } from 'lodash-es';
import { getInstitution } from '@/api/institution'
import { addFinancingInfo } from '@/api/enterprise'
import { useDict, transformDict } from '@/hooks/dict'
import router from '@/router'
const enterpriseList = ref([])
const institutionList = ref([])
const activeName = ref('first')
// const industryNames = computed(() => Array.isArray(form.information?.industryName) ? form.information.industryName.join('/') : '')
const form = reactive({
  enterpriseId: '',
  staffNum: '',
  industry: '',
  registeredCapital: '',
  productId: '',
  productName: '',
  organizationName: "",
  microFlag: 1,
  durationManagement: '',
  corrAddress: '',
  workTelephone: '',
  enterpriseContactor: '',
  contactorTell: '',
  profitState: '',
  legal: {
    name: "",
    legalPerson: '',
    legalLiveAddress: '',
    employmentYears: '',
    shareholdingRatio: ""
  },
  enterpriseContact: {
    contactName: '',
    contactTell: ''
  },
  applyAmountMin: '',
  applyAmountMax: '',
  maturityMin: '',
  maturityMax: '',
  rateMin: '',
  rateMax: '',
  arrivalTimeType: '',
  repaymentType: '',
  guaranteeType: '',
  previousLoanBank: '',
  currentLoanBalance: '',
  information: {
    industryName: [],
    enterpriseId: '',
    corrProvinceSiteId: '',
    corrCitySiteId: '',
    corrAreaSiteId: '',
    corrProvinceSiteName: '',
    corrCitySiteName: '',
    corrAreaSiteName: '',
    legalAddress: '',
    provinceName: '',
    cityName: '',
    areaName: '',
    corrProvinceName: '',
    corrCityName: '',
    corrAreaName: '',
    employmentYears: '',
    shareholdingRatio: 0,
    workTelephone: '',
    enterpriseContactor: '',
    contactorTell: '',
    enterpriseName: '',
    creditCode: '',
    staffNum: '',
    industry: '',

  },
})


// 自定义校验规则 - 融资利率区间
const validateRateRange = (rule, value, callback) => {
  const minRate = form.rateMin
  const maxRate = form.rateMax

  // // 先检查是否都有值
  // if (!minRate || !maxRate) {
  //   callback()
  //   return
  // }

  const min = Number(minRate)
  const max = Number(maxRate)

  // 检查是否为有效数字
  if (isNaN(min) || isNaN(max)) {
    callback(new Error('请输入有效的数字'))
    return
  }

  // 检查范围
  if (min < 0 || min > 100) {
    callback(new Error('最低利率应在0-100%之间'))
    return
  }

  if (max < 0 || max > 100) {
    callback(new Error('最高利率应在0-100%之间'))
    return
  }

  // 检查区间逻辑
  if (min > max) {
    callback(new Error('最低利率不能高于最高利率'))
    return
  }

  callback()
}

// 行业
const industryRef = ref(null)

const industryChanges = (e) => {
  console.log(industryRef.value.presentText);
  form.information.industryName = industryRef.value.presentText
}

const rules = reactive({
  // 步骤1 - 基本信息
  enterpriseId: [
    { required: true, message: '请选择企业名称', trigger: 'change' }
  ],
  'information.staffNum': [
    { required: true, message: '请选择企业人数', trigger: 'change' }
  ],
  'information.industry': [
    { required: true, message: '请选择企业行业', trigger: 'change' }
  ],
  'information.registeredCapital': [
    { required: true, message: '请输入注册资本', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '注册资本必须为数字', trigger: 'blur' }
  ],
  microFlag: [
    { required: true, message: '请选择是否小微企业', trigger: 'change' }
  ],
  'information.depositBank': [
    { required: true, message: '请选择企业开户行', trigger: 'change' }
  ],
  'information.durationManagement': [
    { required: true, message: '请输入已持续经营年限', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '经营年限必须为数字', trigger: 'blur' }
  ],
  'information.corrProvinceSiteId': [
    { required: true, message: '请选择企业所在区域', trigger: 'change' }
  ],
  'information.corrAddress': [
    { required: true, message: '请输入企业经营地址', trigger: 'blur' }
  ],
  'information.workTelephone': [
    { required: true, message: '请输入单位电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^\d{3,4}-\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
  ],
  enterpriseContactor: [
    { required: true, message: '请输入企业联系人', trigger: 'blur' },
    { min: 2, max: 20, message: '联系人姓名长度为2-20个字符', trigger: 'blur' }
  ],
  contactorTell: [
    { required: true, message: '请输入联系人手机', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  'legal.name': [
    { required: true, message: '请输入法定代表人/经营者姓名', trigger: 'blur' }
  ],
  'legal.legalLiveAddress': [
    { required: true, message: '请输入现居住地址', trigger: 'blur' }
  ],
  'legal.employmentYears': [
    { required: true, message: '请输入从业年限', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '从业年限必须为数字', trigger: 'blur' }
  ],
  'legal.shareholdingRatio': [
    { required: true, message: '请输入持股比例', trigger: 'change' }
  ],

  // 步骤2 - 补充信息
  'information.businessPlace': [
    { required: true, message: '请选择营业场所性质', trigger: 'change' }
  ],
  incomeData: [
    { required: true, message: '请选择上一年度开票营业收入', trigger: 'change' }
  ],
  taxAmount: [
    { required: true, message: '请输入上一年度纳税金额', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '纳税金额必须为数字', trigger: 'blur' }
  ],
  'information.declareDeal': [
    { required: true, message: '请输入上一年度报关成交额', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '报关成交额必须为数字', trigger: 'blur' }
  ],
  'information.taxLevel': [
    { required: true, message: '请选择纳税等级', trigger: 'change' }
  ],
  profitState: [
    { required: true, message: '请选择近一年企业盈亏状态', trigger: 'change' }
  ],
  taxYears: [
    { required: true, message: '请输入连续纳税年限', trigger: 'blur' },
    { pattern: /^\d+$/, message: '连续纳税年限必须为整数', trigger: 'blur' }
  ],
  collateralFlag: [
    { required: true, message: '请选择抵押物类型', trigger: 'change' }
  ],
  loanBankName: [
    { required: true, message: '请选择之前贷款银行', trigger: 'change' }
  ],
  loanLeftAmount: [
    { required: true, message: '请输入当前贷款余额', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '贷款余额必须为数字', trigger: 'blur' }
  ],

  // 步骤3 - 融资需求
  applyAmountMin: [
    { required: true, message: '请输入最低融资金额', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '融资金额必须为数字', trigger: 'blur' }
  ],
  applyAmountMax: [
    { required: true, message: '请输入期望融资金额', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '融资金额必须为数字', trigger: 'blur' }
  ],
  maturityMin: [
    { required: true, message: '请输入最短融资期限', trigger: 'blur' },
    { pattern: /^\d+$/, message: '融资期限必须为整数', trigger: 'blur' }
  ],
  maturityMax: [
    { required: true, message: '请输入期望融资期限', trigger: 'blur' },
    { pattern: /^\d+$/, message: '融资期限必须为整数', trigger: 'blur' }
  ],
  rateMin: [
    { required: true, message: '请输入期望融资利率', trigger: 'blur' },
    { pattern: /^\d+(\.\d+)?$/, message: '利率必须为数字', trigger: 'blur' },
    { validator: validateRateRange, trigger: 'blur' }
  ],
  arrivalTimeType: [
    { required: true, message: '请选择期望到账时间', trigger: 'change' }
  ],
  repaymentType: [
    { required: true, message: '请选择期望还款方式', trigger: 'change' }
  ],
  guaranteeType: [
    { required: true, message: '请选择担保类型', trigger: 'change' }
  ]
})
// 字典
const {
  repaymentType: repayWayOptios,
  productMainGuaranteeType: guaranteeTypeOptions,
  taxAmount: taxAmountOptions,
  businessPremises: businessPremisesOptions,
  invoicingOperatingIncome: invoicingOperatingIncome,
  ratepayingLevel: ratepayingLevelOptions,
  enterpriseProfit: enterpriseProfitOptions,
  loanBank: loanBankOptions,
  numberOfCompany: numberOfCompanyOptions,
  expectedArrivalDate: expectedArrivalDateOptions,
  pawnType: pawnTypeOptions,
  enterpriseIndustry: enterpriseIndustryOptions
} = useDict('repaymentType', 'productMainGuaranteeType',
  'enterpriseIndustry',
  'taxAmount', 'loan_term',
  'businessPremises',
  'invoicingOperatingIncome',
  'ratepayingLevel', 'enterpriseProfit', 'pawnType',
  'loanBank', 'numberOfCompany', 'expectedArrivalDate')

const industryOptions = ref([])
const { clearCache, getData } = useApply()
// onUnmounted(() => {
//   clearCache()
// })
const route = useRoute()
onMounted(() => {
  // 初始化数据
  console.log(getData());
  form.productId = route.query.productId
  form.productName = route.query.productName
  form.organizationName = route.query.organizationName



  getEenterpriceList({examineResult: '2'}).then(response => {
    enterpriseList.value = response.data || []
  })
  getInstitution().then(response => {
    institutionList.value = response.rows || []
  })

  getNodeTreeIndustry().then(response => {
    industryOptions.value = response.data || []
  }).catch(error => {
    console.error('获取行业列表失败:', error);
  });
})

// 查询法人
import { getLegalPerson } from '@/api/enterprise'
import { getNodeTreeIndustry } from '@/api/dict'
import useApply from '@/hooks/apply';
import Product from '@/components/product.vue';

function selectMyEnterprise(id) {
  const obj = enterpriseList.value.find(f => f.id === id)
  // 赋值企业信息
  if (obj) {
    Object.assign(form.information, obj)
    form.enterpriseName = obj.enterpriseName
  }
  // 获取法人信息
  getLegalPerson(id).then(res => {
    if (res.code === 200) {
      form.legal = res.data
    }
  })

}
const formRef1 = ref(null)
const formRef2 = ref(null)
const formRef3 = ref(null)

// 企业信息
function finishEnterpriseInfo() {
  formRef1.value.validate((valid) => {
    if (valid) {
      // 验证通过，进入下一步
      next()
    } else {
      // 验证失败
      ElMessage.error('请检查表单填写')
    }
  })
}

// 企业补充信息
function finishSuppleInfo() {
  formRef2.value.validate((valid) => {
    if (valid) {
      // 验证通过，进入下一步
      next()
    } else {
      // 验证失败
      ElMessage.error('请检查表单填写')
    }
  })
}

// 填写融资信息

function finishFinancingInfo() {
  formRef3.value.validate((valid) => {
    if (valid) {
      // 验证通过，进入下一步
      next()
    } else {
      // 验证失败
      ElMessage.error('请检查表单填写')
    }
  })
}
// 融资企业信息预览
function submitAllInfo() {
  // 复制对象修改
  const obj = cloneDeep(form)
  // 赋值申请需求地址
  // obj.information.industryName = obj.information.industryName.join(',')
  obj.provinceName = obj.information.provinceName || ''
  obj.cityName = obj.information.cityName || ''
  obj.areaName = obj.information.areaName || ''
  obj.corrProvinceSiteId = obj.information.corrProvinceSiteId || ''
  obj.corrCitySiteId = obj.information.corrCitySiteId || ''
  obj.corrAreaSiteId = obj.information.corrAreaSiteId || ''
  obj.corrProvinceName = obj.information.corrProvinceName || ''
  obj.corrCityName = obj.information.corrCityName || ''
  obj.corrAreaName = obj.information.corrAreaName || ''
  if(Array.isArray(obj.information.industry)){
    obj.information.industry = obj.information.industry.join(',')
  }
  addFinancingInfo(obj).then(res => {
    if (res.code === 200) {
      ElMessage.success('提交成功')
      router.push({ name: 'myFinanceNeedsPage' })
    } else {
      ElMessage.error(res.message || '提交失败，请稍后再试')
    }
  }).catch(err => {
    ElMessage.error(err.message || '网络错误，请稍后再试')
  })
}
function handleClick() {

}

// 步进器
const step = ref(1)
function next() {
  if (step.value < 4) {
    step.value++
  }
}

function prev() {
  if (step.value > 1) {
    step.value--
  }
}

</script>

<style lang="scss" scoped>
@use '@/assets/styles/tabs_ui.scss';
@use '@/assets/styles/el_form.scss';
</style>
